﻿using UnityEngine;
using System.Collections;
using System;

/// <summary>
/// 对象池，继承对象池句柄
/// </summary>
public class ClassObjPool<T> : ClassObjPoolBase where T : PooledClassObject, new() {
	//where字句后面有new()约束的话，T类型必须有公有的无参的构造函数。
	private static ClassObjPool<T> instance;

	public static T Get()
	{
		if (ClassObjPool<T>.instance == null)
		{
			ClassObjPool<T>.instance = new ClassObjPool<T>();
		}
		//如果对象池中还有对象
		if (ClassObjPool<T>.instance.pool.Count > 0)
		{
			//从最后取一个对象
			T t = (T)((object)ClassObjPool<T>.instance.pool[ClassObjPool<T>.instance.pool.Count - 1]);
			ClassObjPool<T>.instance.pool.RemoveAt(ClassObjPool<T>.instance.pool.Count - 1);
			//这个对象的数量加1
			ClassObjPool<T>.instance.reqSeq += 1u;
			t.usingSeq = ClassObjPool<T>.instance.reqSeq;
			t.holder = ClassObjPool<T>.instance;
			t.OnUse();
			return t;
		}
		T t2 = Activator.CreateInstance<T>();
		ClassObjPool<T>.instance.reqSeq += 1u;
		t2.usingSeq = ClassObjPool<T>.instance.reqSeq;
		t2.holder = ClassObjPool<T>.instance;
		t2.OnUse();
		return t2;
	}

	/// <summary>
	/// 回收进入对象池
	/// </summary>
	/// <param name="obj">Object.</param>
	public override void Release(PooledClassObject obj)
	{
		T t = obj as T;
		obj.usingSeq = 0u;
		obj.holder = null;
		this.pool.Add(t);
	}
}
